package com.ruigi.control;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruigi.Utils.ValidateCodeUtils;
import com.ruigi.pojo.R;
import com.ruigi.pojo.User;
import com.ruigi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class Usercontrol {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserService userService;

    //发送手机验证码短信
    @PostMapping("/sendMsg")
    public R<String> send(@RequestBody User user, HttpSession session) {
        //拿到手机号
        String phone = user.getPhone();

        if (phone != null) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            System.out.println(code);


            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);


            return R.success("成功");


        }


        return null;
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        System.out.println(map.toString());
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
//        Object sessionphone = session.getAttribute(phone);
        Object sessionphone = redisTemplate.opsForValue().get(phone);
        if (sessionphone != null && sessionphone.equals(code)) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User one = userService.getOne(queryWrapper);
            if (one == null) {
                User user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
                session.setAttribute("user", user.getId());

                redisTemplate.delete(phone);


                return R.success(user);

            }
            session.setAttribute("user", one.getId());
            redisTemplate.delete(phone);
            return R.success(one);
        }


        return R.error("失败");

    }

    //用户退出
    @PostMapping("/loginout")
    public R<String> logout(HttpSession session) {
        session.removeAttribute("user");
        return R.success("退出成功");
    }
}
